package xcmg.device.service.ratingManager;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.ratingManager.RatingConfigTimeDO;
import xcmg.device.dao.mapper.ratingManager.RatingConfigTimeDOMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.enums.RatingConfigTimeEnum;
import xcmg.device.service.vo.ratingManager.RatingConfigTimeVO;
import yb.ecp.fast.feign.FastGenClient;


/**
 * Created by wrg on 2019/7/10.
 */
@Service
public class RatingConfigTimeService {
    @Autowired
    private RatingConfigTimeDOMapper ratingConfigTimeDOMapper;

    @Autowired
    private FastGenClient genClient;

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode add(RatingConfigTimeVO ratingConfigTimeVO) throws Exception {
        RatingConfigTimeDO ratingConfigTimeDO = ratingConfigTimeDOMapper.selectByRatingIdType(ratingConfigTimeVO.getRatingId(), ratingConfigTimeVO.getType());
        if (null != ratingConfigTimeDO){
            return ErrorCode.InfoExist;
        }

        RatingConfigTimeDO record = new RatingConfigTimeDO();
        BeanUtils.copyProperties(ratingConfigTimeVO, record);
        String id = genClient.newGuidText().getValue();
        if (StringUtils.isBlank(id)) {
            return ErrorCode.IllegalArument;
        }
        record.setId(id);
        Integer type = record.getType();
        record.setTypeDes(RatingConfigTimeEnum.getDescByCode(type));
        return ratingConfigTimeDOMapper.insertSelective(record) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode update(RatingConfigTimeVO ratingConfigTimeVO) throws Exception {
        RatingConfigTimeDO record = new RatingConfigTimeDO();
        record.setId(ratingConfigTimeVO.getId());
        record.setStartTime(ratingConfigTimeVO.getStartTime());
        record.setEndTime(ratingConfigTimeVO.getEndTime());
        if (null != ratingConfigTimeVO.getUrgentOrderMaxQty()){
            record.setUrgentOrderMaxQty(ratingConfigTimeVO.getUrgentOrderMaxQty());
        }
        return ratingConfigTimeDOMapper.updateByPrimaryKeySelective(record) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    public RatingConfigTimeVO item(String ratingId,Integer type) {
        RatingConfigTimeDO ratingConfigTimeDO = ratingConfigTimeDOMapper.selectByRatingIdType(ratingId, type);
        RatingConfigTimeVO ratingConfigTimeVO = new RatingConfigTimeVO();
        if (null != ratingConfigTimeDO) {
            BeanUtils.copyProperties(ratingConfigTimeDO, ratingConfigTimeVO);
        }
        return ratingConfigTimeVO;
    }
}
